<?php


namespace Lib\Model;


use Lib\Component\Factory;
use Lib\Component\Mysql;

class Base
{
    public static function executeInsert($sql, $data, &$error)
    {
        $stmt = self::query($sql, $data, $error);
        if ($stmt === false) {
            return false;
        }
        $insert_id = $stmt->insert_id;
        $stmt->close();
        return $insert_id;
    }

    public static function executeDelete($sql, $data, &$error)
    {
        $stmt = self::query($sql, $data, $error);
        if ($stmt === false) {
            return false;
        }
        $affected_rows = $stmt->affected_rows;
        $stmt->close();
        return ($affected_rows) > 0;
    }

    public static function executeUpdate($sql, $data, &$error)
    {
        $stmt = self::query($sql, $data, $error);
        if ($stmt === false) {
            return false;
        }
        $affected_rows = $stmt->affected_rows;
        $stmt->close();
        return ($affected_rows) > 0;
    }

    public static function executeSelect($sql, $data, &$error)
    {
        $stmt = self::query($sql, $data, $error);
        if ($stmt === false) {
            return false;
        }
        $result = $stmt->get_result();
        $stmt->close();
        $list = array();
        for ($i = 0; $i < $result->num_rows; $i++) {
            $list[] = $result->fetch_assoc();
        }
        return $list;
    }

    /**
     * 绑定参数执行sql
     * @param $sql
     * @param $data
     * @return mixed
     * @throws \ReflectionException
     */
    public static function query($sql, $data, &$error)
    {
        $factory = Factory::getFactory();
        $mysql = $factory->get(Mysql::class);
        $stmt = $mysql->prepare($sql);
        if ($stmt === false) {
            $error = $mysql->error;
            return $stmt;
        }
        if (count($data) > 0) {
            $bind_names[] = '';
            foreach ($data as &$datum) {
                $bind_names[] = &$datum;
                $bind_names[0] .= substr(gettype($datum), 0, 1);
            }
            call_user_func_array(array($stmt, 'bind_param'), $bind_names);
        }

        if (!$stmt->execute()) {
            $error = $stmt->error;
            return false;
        }
        return $stmt;
    }
}